package cn.ecnu.auction.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.TimeUnit;



import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import ToolPackage.Json;

import cn.ecnu.auction.db.DbConnection;
import cn.ecnu.auction.po.Goods;

public class GoodsDAO {
	private static Logger logger = Logger.getLogger(GoodsDAO.class);
	
	/**
	 * 新增拍卖品
	 * @param gname 拍卖品名称
	 * @param description 描述
	 * @param startPrice 起拍价
	 * @param lastingTime 拍卖时间
	 * @param uid 拍卖品提供者
	 * @result result >= 0 正确  result = -1 错误
	 */
	public int addGood(String gname, String description, double startPrice, String startTime, String lastingTime,int uid,String type){
		Connection conn = DbConnection.getConnection();
		String sql = "insert into goods( gname, description, startPrice, startTime, lastingTime , ownerid ,currentPrice,type,result) values(?, ?, ?, ?, ?, ?, ?,?,0)";
		int result = 0;
		try {
			PreparedStatement pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, gname);
			pstmt.setString(2, description);
			pstmt.setDouble(3, startPrice);
			pstmt.setString(4, startTime );
			pstmt.setString(5, lastingTime);		
			pstmt.setInt(6, uid);
			pstmt.setDouble(7, startPrice);
			pstmt.setString(8, type);
			logger.info(pstmt);
			result = pstmt.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
			result = -1;
		} finally {
			DbConnection.closeConnection(conn);
		}
		return result;
	}
	
	
	public JSONArray getGoods(){
		Connection conn = DbConnection.getConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "select * from goods";
		
		JSONArray jsonArray = new JSONArray();
		JSONObject json;
		try {
			pstmt=conn.prepareStatement(sql);
		rs = pstmt.executeQuery();
		while (rs.next()) {
			System.out.println("~~~~~~~~~~~~~~");
			json=new JSONObject();
			json.put("gid", rs.getInt("gid"));
			json.put("gname", rs.getString("gname"));
			json.put("type", rs.getString("type"));
			
			Date currentDate = new Date();

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String startDateStr =rs.getString("startTime");
			
			Date startDate = sdf.parse(startDateStr);
			double lasting = rs.getDouble("lastingTime");
			Calendar c = Calendar.getInstance();
			c.setTime(startDate);
			c.add(Calendar.MINUTE, (int) (lasting*60));
			
			Date endDate=c.getTime();
			
			
			long millis=(endDate.getTime()-currentDate.getTime());
			int hour= (int)TimeUnit.MILLISECONDS.toHours(millis);
			millis=millis-(int)TimeUnit.MILLISECONDS.toHours(millis)*60*60*1000;
			
			int minute= (int)TimeUnit.MILLISECONDS.toMinutes(millis);
			millis=millis-(int)TimeUnit.MILLISECONDS.toMinutes(millis)*60*1000;
			
			
			int second= (int)TimeUnit.MILLISECONDS.toSeconds(millis);
			json.put("leftHours", hour);
			json.put("leftMins",minute);
			json.put("leftSecs", second);
			jsonArray.put(json);
			}
		} catch (Exception e) {
				e.printStackTrace();
				logger.error(e);
		   } finally {
				DbConnection.closeConnection(conn);
			}
		  
		
		return jsonArray;
	}
	
	
	public JSONObject getGoodsById(int gid){
		Connection conn = DbConnection.getConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "select * from goods where gid="+gid;
		
		JSONArray jsonArray = new JSONArray();
		JSONObject json=null;
		try {
			pstmt=conn.prepareStatement(sql);
		    rs = pstmt.executeQuery();
		    if (rs.next()) {
				json=new JSONObject();
				json.put("gid", rs.getInt("gid"));
				json.put("gname", rs.getString("gname"));
				json.put("type", rs.getString("type"));
				json.put("startPrice",rs.getDouble("startPrice"));
				json.put("description", rs.getString("description"));
				json.put("currentPrice",  rs.getString("currentPrice"));
			
			    String sql2 = "select * from user where userid="+rs.getInt("ownerid");
			
				pstmt=conn.prepareStatement(sql2);
				ResultSet rs2 = pstmt.executeQuery();
				rs2.next();
				json.put("ownerName", rs2.getString("userName"));
			
			
			    Date currentDate = new Date();

				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String startDateStr =rs.getString("startTime");
				
				Date startDate = sdf.parse(startDateStr);
				double lasting = rs.getDouble("lastingTime");
				Calendar c = Calendar.getInstance();
				c.setTime(startDate);
				c.add(Calendar.MINUTE, (int) (lasting*60));
				
				Date endDate=c.getTime();
				
				long millis=(endDate.getTime()-currentDate.getTime());
				System.out.println("~~~~~~~~~"+ currentDate.toString()+"  " +millis);
				int hour= (int)TimeUnit.MILLISECONDS.toHours(millis);
				millis=millis-(int)TimeUnit.MILLISECONDS.toHours(millis)*60*60*1000;
				
				int minute= (int)TimeUnit.MILLISECONDS.toMinutes(millis);
				millis=millis-(int)TimeUnit.MILLISECONDS.toMinutes(millis)*60*1000;
				
				
				int second= (int)TimeUnit.MILLISECONDS.toSeconds(millis);
				json.put("leftHours", hour);
				json.put("leftMins",minute);
				json.put("leftSecs", second);
				
			}
		} 
		catch (Exception e) {
				e.printStackTrace();
				
				logger.error(e);
		} finally {
				DbConnection.closeConnection(conn);
		}
		
		return json;		
	}

	public int updateResult(int gid)
	{
		int returnresult = 1;
		
		Connection conn = DbConnection.getConnection();
		PreparedStatement pstmt = null;
		PreparedStatement pstmt2 = null;
	
		String sql = "update Goods set result = 1 where gid=" + gid;
		String sql2 = "update Bid set result = 1 where gid=" + gid;
		
		try {
			pstmt=conn.prepareStatement(sql);
			pstmt2=conn.prepareStatement(sql2);
			logger.info(pstmt);
			pstmt.executeUpdate();
			pstmt2.executeUpdate();
		} 
		catch (Exception e) {
			returnresult=0;
			e.printStackTrace();
			logger.error(e);
		} finally {
			DbConnection.closeConnection(conn);
		}
		
		return returnresult;
	}
}
